package br.com.teste;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Driver;

/**
 * Servlet implementation class TesteServlet
 */
@WebServlet("/TesteServlet")
public class TesteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TesteServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				
		
			try {
				Connection cn = this.getConnection();
				
				PreparedStatement st = cn.prepareStatement("select * from teste");
				
				ResultSet resultSet =  st.executeQuery();

				ArrayList<String> lista = new ArrayList<String>();
				
				while (resultSet.next()) {
					lista.add(resultSet.getString("campo1"));
					lista.add(resultSet.getString("campo2"));
					
				}
				
				
				for (int i = 0; i < lista.size(); i++) {
				//	response.getWriter().println(lista.get(i));
				}

				
				request.setAttribute("retornoBanco1", lista.get(0));
				
				request.setAttribute("retornoBanco2", lista.get(2));
				
				RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/teste.jsp");
				dispatcher.forward(request, response);

				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	
	public Connection getConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {

		Class.forName("com.mysql.jdbc.Driver").newInstance();  
        
	    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", "admin");

	    System.out.println("Connected to database");
	    return conn;
	}
}
